package com.j.lemon.learn.thread.NIO;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SimpleServer {
    public static void main(String[] args) throws IOException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        ServerSocket serverSocket = new ServerSocket(8089);
        while(true){
            Socket socket = serverSocket.accept();
            executorService.execute(new MyThread(socket));
        }


    }
}

class MyThread implements Runnable{
    private Socket socket;
    public MyThread(Socket socket){
        this.socket=socket;
    }
    @Override
    public void run() {
        try {
            System.out.println(Thread.currentThread().getName()+"正在执行任务");
            InputStream is = socket.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            long e = System.currentTimeMillis();

            BufferedReader br = new BufferedReader(isr);
            String read = br.readLine();
            long b = System.currentTimeMillis();
            System.out.println("客户端说："+read);
            System.out.println("spend:"+(b-e)+"ms");
            OutputStream o =socket.getOutputStream();
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(o);
            PrintWriter printWriter = new PrintWriter(outputStreamWriter,true);
            printWriter.println("你已成功连接~");
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(socket!=null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
